package num707;

/**
 * @author : DuJiabao
 * @Date : 2021/1/25 14:54
 * @Project : sword-finger-offer
 * @File : null.java
 * @Desc :
 */
class MyLinkedList {

    ListNode head = new ListNode(0);
    int length = 0;

    /**
     * Initialize your data structure here.
     */
    public MyLinkedList() {

    }

    /**
     * Get the value of the index-th node in the linked list. If the index is invalid, return -1.
     * 遍历到该位置
     */
    public int get(int index) {
        if (index >= length || index < 0) return -1;
        ListNode point = head.next;
        for (int i = 0; i < index; i++) {
            point = point.next;
        }
        return point.val;
    }

    /**
     * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
     * 直接在头节点后面追加
     */
    public void addAtHead(int val) {
        ListNode point = new ListNode(val);
        point.next = head.next;
        head.next = point;
        length++;
    }

    /**
     * Append a node of value val to the last element of the linked list.
     * 遍历到尾结点之后，追加
     */
    public void addAtTail(int val) {
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = new ListNode(val);
        length++;
    }

    /**
     * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
     遍历到该元素之后，追加
     */
    public void addAtIndex(int index, int val) {
        if (index > length || index < 0) return;
        ListNode fast = head.next;
        ListNode slow = head;
        for (int i = 0; i < index; i++) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode point = new ListNode(val);
        point.next = fast;
        slow.next = point;
        length++;
    }

    /**
     * Delete the index-th node in the linked list, if the index is valid.
     * 遍历到指定index，然后删除
     */
    public void deleteAtIndex(int index) {
        if (index >= length || index < 0) return;
        ListNode point = head;
        // 本身就是在伪头节点，因此本身就在-1位置。因此到达index-1的位置，就可以实现删除结点
        for (int i = 0; i < index; i++) {
            point = point.next;
        }
        point.next = point.next.next;
        length--;
    }
}
